$(document).ready(function () {
    //获取父分类列表
    getParentCategoryList();

});
//数据表格
layui.use(['table','form'], function() {
    let table = layui.table
        ,form = layui.form;


    form.on('submit(creatCategory)',function () {
        createCategory();
    });

    table.render({
        elem: '#categoryList'
        ,method:"post"
        , url: '/categoryList'
        , toolbar: '#topTools' //开启头部工具栏，并为其绑定左侧模板
        , title: '分类列表'
        ,totalRow: true
        ,request:{
            pageName: 'curPage',
            limitName:'pageSize'
        },parseData:function (res) {
            return {
                "code": res.code==200? 0 : -1,
                "msg": "",
                "count":res.data.count,
                "data":res.data.data
            }
        }
        , cols: [
            [
                {field: 'id', title: 'ID', fixed: 'left',width:60, unresize: true, sort: true}
                , {field: 'name', title: '分类名',edit: 'text',width:100}
                , {field: 'type', title: '分类类型',edit: 'text',width:100,templet:"<div>{{(d.type == 1)?'一级分类':'二级分类'}}</div>>"}
                , {field: 'slogan', title: '口号',edit: 'text',width:250}
                , {field: 'cat_image', title: '分类图片(URL)',edit: 'text',width:100}
                , {field: 'parentId', title: '父分类ID',edit: 'text',width:100}
                , {field: 'createTime', title: '创建日期',width:100,templet:"<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss')}}</div>"}
                , {field: 'status', title: '状态',width:100,templet:"<div>{{(d.status == 1)?'启用':'禁用'}}</div>>"}
                , {fixed: 'right', title: '操作',width:180, toolbar: '#categoryOperator'}
            ]]
        , page: true
        ,done:function (res,curr,count) {
            // console.log(res,curr,count);

        }
    });
    //监听头部工具事件
    table.on('toolbar(categoryList)',function (obj) {
        // console.log(obj.event)
        switch (obj.event) {
            case 'createNewCategory':
                createCategoryModel()
                break;
            case 'searchType':
                searchCategory();
                break;

        }
        function searchCategory() {
            let key = $("#searchCategoryName").val();
            table.reload('categoryList', {
                method:"post"
                ,where: {
                    'name': key,
                    'type':type
                }
                , page: {
                    curr: 1
                }
            });
            // $("#searchCategoryName").val(key);
            //重设表单属性，参数1为class="layui-form" 所在元素属性 lay-filter="" 对应的值,
            // 参数2为表单内元素name属性与value属性的键值对
            form.val("categoryForm",{
                "searchCategoryName":key,
                "itemType":type
            });
        }
    });
    //监听行工具事件
    table.on('tool(categoryList)', function(obj){
        let data = obj.data;
        // let id = obj.id;
        // let parentId = obj.parentId;
        // let title =  obj.title;
        // let url = obj.url;
        if(obj.event === 'del'){
            layer.confirm('确定要删除该分类吗？', function(index){
                obj.del();
                $.ajax({
                    url:"/delCategory",
                    method:"post",
                    data:JSON.stringify(data),
                    dataType:"json",
                    contentType: "application/json;charset=utf-8;",
                    success:function (data) {
                        if (data =="1"){
                            alert("删除成功！");
                            location.reload()
                        }else {
                            alert("删除失败！");
                        }
                    }
                });
                layer.close(index);
            });
        }else if(obj.event === "edit"){
            $.ajax({
                url:"/editCategory",
                method:"post",
                charset:"UTF-8",
                dataType:"json",
                contentType:"application/json;charset=utf-8;",
                data:JSON.stringify(data),
                success:function (data) {
                    if (data == "1"){
                        alert("修改分类成功");
                        location.reload();
                        layer.close(layer.index);
                    }else {
                        alert("修改分类失败");
                        layer.close(layer.index);
                    }
                }
            });
        }else if(obj.event=== "enable"){
            $.ajax({
                url:"/enableCategory",
                method:"post",
                charset:"UTF-8",
                dataType:"json",
                contentType:"application/json;charset=utf-8;",
                data:JSON.stringify(data),
                success:function (data) {
                    if (data == "1"){
                        alert("启用分类成功");
                        location.reload();
                        layer.close(layer.index);
                    }else {
                        alert("启用分类失败");
                        layer.close(layer.index);
                    }
                }
            });
        }else if(obj.event==="disable"){
            $.ajax({
                url:"/disableCategory",
                method:"post",
                charset:"UTF-8",
                dataType:"json",
                contentType:"application/json;charset=utf-8;",
                data:JSON.stringify(data),
                success:function (data) {
                    if (data == "1"){
                        alert("禁用分类成功");
                        location.reload();
                        layer.close(layer.index);
                    }else {
                        alert("禁用分类失败");
                        layer.close(layer.index);
                    }
                }
            });
        }
    });

    //获取选中的单选框值
    let type ;
    // $("input[name='']").val();
    form.on('radio(itemType)', function (obj) {
        type = obj.value ;
        // console.log(type)
    })
});



function cleanerCategoryText() {
    $("input[name='name']").val("");
}

//创建分类
function createCategory() {
    let name = $("input[name='name']").val();
    let type = $("#categoryTypeSelect").val();
    let catImage = $("input[name='catImage']").val();
    let parentId =  $("#parentCategorySelect").val();
    let categoryJson = {"name":name,"type":type,"parentId":parentId,"catImage":catImage};
    $.ajax({
        url:"/createNewCategory",
        method:"post",
        charset:"UTF-8",
        dataType:"json",
        contentType:"application/json;charset=utf-8;",
        data:JSON.stringify(categoryJson),
        success:function (data) {
            if (data == "1"){
                alert("新增分类成功");
                cleanerCategoryText();
                location.reload();
                layer.close(layer.index);
            }else {
                alert("新增分类失败");
                cleanerCategoryText();
                layer.close(layer.index);
            }
        }
    });
}




function createCategoryModel() {
    layui.use(['layer'], function () {
        let layer = layui.layer, $ = layui.$;
        layer.open({
            type: 1,
            anim:4,
            area:['auto','auto'],
            title: '新增分类',
            shadeClose: false,
            content: $('#createCategory')
        });
    });
}


function getParentCategoryList() {
    $.ajax({
        url:"/getParentCategory",
        method:"post",
        charset: "UTF-8",
        async:false,
        success:function (res) {
            let parentCategorySelect = $("#parentCategorySelect");
            parentCategorySelect.empty();
            let parentCategoryList = res.data;
            $.each(parentCategoryList,function (index,value) {
                parentCategorySelect.append( "<option value='" + value.id + "'"+">" + value.name + "</option>");
            });

        }

    })
}